/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable react/prop-types */
import React, { useState, useEffect } from 'react';
import {
  Message,
  PopConfirm,
  Icon,
  Divider,
  Button,
  Menu,
  Overlay,
  Rating,
  Input,
  Balloon,
} from '@teamix/ui';
import { YunxiaoIcon, Lead } from '@alife/devops-ui';
import { getAllUrlParams } from '../../utils/ahooks';
import { navigate } from 'utils/router';
import utils from 'utils/index';
import track from 'utils/track';
import './index.scss';
import { getSearchHistory, searchPostUserFeedBack } from '../../action';
import Editor from '../../myEditor';
import { setIntroPointState } from 'api';
import exceed from 'utils/apimap';

const { NotifyCard } = Lead;
const Search_Header = (props) => {
  const [commentValue, setcommentValue] = useState('');
  const [RatingValue, setRatingValue] = useState(5);
  const [historyListisShow, sethistoryListisShow] = useState(false);
  const [visiblePopconfim, setvisiblePopconfim] = useState(false);
  const { headerModeStatus, changeModeStatus } = props;
  const [recentSearchList, setrecentSearchList] = useState([]);
  const searchTips = () => {
    const { id } = window.FORCE.user;
    const SESSION_LEAD_VISITED = `session-cloud-search-rule-visited/${id}`;
    if (utils.getCookie(SESSION_LEAD_VISITED) !== 'false') {
      setvisiblePopconfim(true);
    }
    const sidebarElement = document.querySelector('#tb-common-sidebar-wrapper');
    if (sidebarElement) {
      sidebarElement.remove();
      document.body.style.paddingLeft = 0;
      document.body.setAttribute('style', 'padding-left: 0px');
    }
  };
  useEffect(() => {
    searchTips();
    const status =
      utils.getUrlParam({ name: 'is_dsl', type: 'search' }) === 'true' ? 'ordinary' : 'grammer';
    changeModeStatus(status);
  }, [props.headerModeStatus]);
  const description = (
    <>
      <p>规则说明：</p>
      <ul className="codeup_search_rule_desc">
        <li>仅展示有权限查看的数据</li>
        <li>仅展示代码库默认分支数据</li>
        <li>若新增文件，需等待约5分钟后即可搜索</li>
      </ul>
      <p>不支持搜索的场景：</p>
      <ul className="codeup_search_rule_desc">
        <li>单文件超过 1M </li>
        <li>文件类别无法识别</li>
        <li>代码库已开启加密</li>
      </ul>
    </>
  );
  useEffect(() => {
    getSearchHistory().then((res) => {
      res.shift();
      setrecentSearchList(res.filter((i) => i.historyType === 'search'));
    });
    const params = getAllUrlParams(window.location.href);
    if (params && params.inputtext) {
      props.getSearchOnChange(decodeURIComponent(params.inputtext));
    }
    if (params && params.headerselectvalue) {
      props.headerSelectOnChange(params.headerselectvalue, true);
    }
    if (params && params.searchcodestorehousedata) {
      try {
        props.getCodeHouseValue(
          {
            value: JSON.parse(decodeURIComponent(params.searchcodestorehousedata)),
            isRegexp: false,
          },
          true,
        );
      } catch (error) {
        props.getCodeHouseValue(
          { value: [decodeURIComponent(params.searchcodestorehousedata)], isRegexp: false },
          true,
        );
      }
    }
    if (params && params.filter && decodeURIComponent(params.filter)) {
      const filterObj = JSON.parse(decodeURIComponent(params.filter));
      filterObj.type && props.setSearchType(filterObj.type);
      filterObj.isMine && props.headerSelectOnChange('mine');
      filterObj.regexp &&
        props.getCodeHouseValue({
          isRegexp: true,
          value: filterObj.regexp,
          name: filterObj.regexp,
        });
    }
    if (
      params &&
      (params.inputtext || params.headerselectvalue || params.searchcodestorehousedata)
    ) {
      props.getSearchData();
    }
  }, []);

  const onpressEnter = () => {
    props.headerInputStatusChange(false);
    if (props.headerInputValue.length > 1000) {
      return Message.error({ title: '查询内容不能超过1000个字符' });
    }
    track({
      action: 'do_search',
      page: 'Search-Page',
      type:
        // eslint-disable-next-line no-nested-ternary
        props.searchType === 'code'
          ? 'code_snippet'
          : // eslint-disable-next-line no-nested-ternary
          props.searchType === 'repo'
          ? 'code_repo'
          : props.searchType === 'commit'
          ? 'code_commit'
          : 'code_mr', // 右边选中的筛选类型，代码片段:code_snippet，代码库:code_repo，提交:code_commit，合并请求:code_mr
      control: props.headerInputValue,
    });
    const searchcodestorehousedata = utils.getUrlSearchParam('searchcodestorehousedata') || '';
    const filter = utils.getUrlSearchParam('filter') || '';
    if (props.headerInputValue === '') {
      props.closeErrorMessage();
    }
    props.headerInputValue.length !== 1 &&
      navigate(
        `${window.location.origin}${window.location.pathname}?inputtext=${encodeURIComponent(
          props.headerInputValue,
        )}&searchcodestorehousedata=${encodeURIComponent(
          searchcodestorehousedata,
        )}&filter=${encodeURIComponent(filter)}&is_dsl=${headerModeStatus === 'grammar'}`,
      );
    props.headerInputValue.length !== 1 && props.getSearchData();
  };
  const renderRecentSearchList = () => {
    return (
      <Menu.Group label={''} key="projects" style={{ display: 'none' }}>
        {recentSearchList &&
          recentSearchList.map((item) => (
            <Menu.Item
              key={item.id}
              className={item.active ? 'active' : null}
              onClick={() => {
                props.getSearchOnChange(item.queryString);
                props.headerInputStatusChange(false);
                const searchcodestorehousedata =
                  utils.getUrlSearchParam('searchcodestorehousedata') || '';
                const filter = utils.getUrlSearchParam('filter') || '';
                navigate(
                  `${window.location.origin}${
                    window.location.pathname
                  }?inputtext=${encodeURIComponent(
                    item.queryString,
                  )}&searchcodestorehousedata=${encodeURIComponent(
                    searchcodestorehousedata,
                  )}&filter=${encodeURIComponent(filter)}&is_dsl=${headerModeStatus === 'grammar'}`,
                );
                props.getSearchData();
              }}
            >
              <YunxiaoIcon
                type={'a-advancesearch'}
                style={{ marginRight: '13px', marginLeft: '2px' }}
              />
              {item.queryString}
            </Menu.Item>
          ))}
      </Menu.Group>
    );
  };
  const renderErrorMessage = () => {
    const { start, stop } = props?.dslErrorMessage?.errorContext;
    const value = decodeURIComponent(utils.getUrlParam({ name: 'inputtext', type: 'search' }));
    return (
      <Message
        className="dsl-error"
        afterClose={props.closeErrorMessage}
        title={
          <div style={{ marginTop: '2px' }}>
            <span className="dsl-error-tip">语法格式有误/不支持该语法，请修改后重试</span>
            <a
              className="more-instruction"
              href="https://help.aliyun.com/document_detail/419325.html"
              target="_blank"
              style={{ color: '#1b9aee', marginLeft: '370px' }}
              rel="noreferrer"
            >
              更多说明
            </a>
          </div>
        }
        type="notice"
        size="large"
        style={{ width: '760px' }}
      >
        <div
          className="dsl-error-message"
          dangerouslySetInnerHTML={{
            __html: `<span>${value?.slice(0, start)?.replace(/\s/g, '&nbsp;')}</span>
                <span class='errorTip'>
              ${value?.slice(start, stop + 1)?.replace(/\s/g, '&nbsp;')}
    </span>
    <span>${value?.slice(stop + 1)?.replace(/\s/g, '&nbsp;')}</span>`,
          }}
        />
      </Message>
    );
  };
  const renderFeedbackContent = () => {
    return (
      <div className="search_header_feedback_content">
        <Rating
          defaultValue={5}
          size="large"
          value={RatingValue}
          onChange={(val) => setRatingValue(val)}
        />
        <Input.TextArea
          value={commentValue}
          onChange={(val) => setcommentValue(val)}
          maxLength={1000}
          placeholder="留下你的感受和建议"
          aria-label="TextArea"
          size="large"
          style={{ width: '232px', height: '80px', marginTop: '16px' }}
        />
      </div>
    );
  };
  const renderSwitch = () => {
    return (
      <Balloon.Tooltip
        popupStyle={{ marginLeft: '24px' }}
        trigger={
          <Button text >
            <YunxiaoIcon type="switch-line" style={{ marginRight: 8, marginLeft: 10 }} />
            {headerModeStatus === 'ordinary' ? '语法模式' : '普通模式'}
          </Button>
        }
        align="t"
      >
        切换至{headerModeStatus === 'ordinary' ? '语法模式' : '普通模式'}
      </Balloon.Tooltip>
    );
  };
  const nextTimeBtn = () => {
    exceed
      .fetch({
        api: 'search.clear_search_count',
      })
      .then((res) => {
        if (res) {
          props.changeFeedback({ isShow: false, planId: '' });
        }
      });
  };
  const finishedBtn = () => {
    searchPostUserFeedBack({ satisfactionStar: RatingValue, feedBackContent: commentValue }).then(
      (res) => {
        if (res) {
          props.changeFeedback({ isShow: false, planId: '' });
        }
      },
    );
    setIntroPointState('codeup_common_pop_up', { plan_id: props.searchFeedback.planId }).then(
      (res) => {
        if (res.state) {
          props.changeFeedback({ isShow: false, planId: '' });
        }
      },
    );
  };
  return (
    <div
      className="codeup_search_header"
      style={{
        backgroundImage:
          headerModeStatus === 'ordinary'
            ? 'url("https://img.alicdn.com/imgextra/i3/O1CN010Dftqj1WgET3kUXYt_!!6000000002817-2-tps-2880-310.png")'
            : 'url("https://img.alicdn.com/imgextra/i4/O1CN01znBWxr1nQ3x0vr4Tm_!!6000000005083-2-tps-2880-310.png")',
      }}
    >
      <div className="codeup_search_rule" />
      <div className="codeup_search_component">
        <div className="codeup_search_header_input">
          <div className="codeup_search_header_desc_link">
            <PopConfirm
              type="info"
              align="bl"
              title=""
              visible={visiblePopconfim}
              popupClassName="search_popconfim"
              content={description}
              triggerType="click"
              trigger={
                <Button text>
                  <YunxiaoIcon type="information-line" style={{ marginRight: 3 }} />
                  规则说明
                </Button>
              }
              offset={[0, 0]}
              locale={{ confirm: '我知道了' }}
              cancelProps={{ id: 'popconfimId' }}
              onVisibleChange={(v) => {
                v && setvisiblePopconfim(true);
              }}
              onConfirm={() => {
                setvisiblePopconfim(false);
                const { id } = window.FORCE.user;
                const SESSION_LEAD_VISITED = `session-cloud-search-rule-visited/${id}`;
                utils.setCookie(SESSION_LEAD_VISITED, false, 100 * 365 * 24 * 3600 * 1000, {
                  domain: '.aliyun.com',
                  path: '/',
                });
              }}
            />
            <Divider direction="ver" />
            <Button
              text
              onClick={() =>
                props.changeFeedback({ isShow: true, planId: props.searchFeedback.planId })
              }
            >
              <YunxiaoIcon type="message-line" style={{ marginRight: 3 }} />
              我要反馈
            </Button>
            <NotifyCard
              style={{ backgroundColor: '#fff' }}
              height={340}
              width={280}
              top={150}
              right={40}
              visible={props.searchFeedback.isShow}
              title="搜索使用满意度"
              btns={[
                { type: 'normal', text: '下次再说', onClick: () => nextTimeBtn() },
                { type: 'primary', text: '提交', onClick: () => finishedBtn() },
              ]}
              type="lite"
              headerImg={
                'https://img.alicdn.com/imgextra/i1/O1CN01Yd88Xk1JJhyyJoY5h_!!6000000001008-55-tps-280-122.svg'
              }
            >
              {renderFeedbackContent()}
            </NotifyCard>
          </div>
          <div
            className="codeup_search_inputI"
            style={{ borderColor: headerModeStatus === 'ordinary' ? '#e8e8e8' : '#00bfff' }}
          >
            <Icon
              type="search"
              style={{ margin: 4, paddingLeft: 20, color: 'var(--color-fill1-6, #8b8b8b)' }}
            />
            <Editor
              changeEditorFocusObj={props.changeEditorFocusObj}
              changehistoryListisShow={sethistoryListisShow}
              headerModeStatus={headerModeStatus}
              placeholderIsShow={props.headerInputValue === ''}
              placeholder={
                headerModeStatus === 'ordinary'
                  ? '请输入关键词搜索'
                  : '支持搜索多种语法及逻辑 单击 Enter 搜索结果'
              }
              onChange={(value, e) => {
                if (e.changes[0].text.includes('\n')) {
                  props.headerInputStatusChange(true);
                  value = value.replace(/\r|\n/g, '');
                  props.getSearchOnChange(value);
                  onpressEnter();
                  props.changeOneTip(value);
                } else {
                  props.headerInputStatusChange(true);
                  props.getSearchOnChange(value);
                }
              }}
              editorStyle={{
                height: '70px',
                width: '100%',
              }}
              value={props.headerInputValue}
            />
            <div
              onClick={() => {
                changeModeStatus(headerModeStatus);
                const filter = utils.getUrlSearchParam('filter') || '{}';
                const filterObj = JSON.parse(filter);
                const filterStr = JSON.stringify(filterObj);
                const inputtext = utils.getUrlSearchParam('inputtext');
                const searchcodestorehousedata =
                  utils.getUrlSearchParam('searchcodestorehousedata') || '';
                navigate(
                  `/search?inputtext=${encodeURIComponent(
                    inputtext,
                  )}&searchcodestorehousedata=${encodeURIComponent(
                    searchcodestorehousedata,
                  )}&filter=${encodeURIComponent(filterStr)}&is_dsl=${
                    headerModeStatus !== 'grammar'
                  }`,
                );
              }}
              style={{ marginRight: 20 }}
            >
              {renderSwitch()}
            </div>
          </div>
          <Overlay
            visible={historyListisShow}
            target={() => document.querySelector('.codeup_search_inputI')}
            safeNode={() => document.querySelector('.codeup_search_inputI')}
          >
            {!props.headerInputValue && recentSearchList.length > 0 && (
              <div className="search_menu_list">
                <Menu style={{ width: '804px' }} autoFocus={false}>
                  {renderRecentSearchList()}
                </Menu>
              </div>
            )}
          </Overlay>

          <div className="search_one_string_tips">
            {props.headerOneTips ? '输入内容太少啦，请输入2个及以上字符进行搜索' : null}
          </div>
          {props.dslErrorMessage ? renderErrorMessage() : null}
        </div>
      </div>
    </div>
  );
};

export default Search_Header;
